[<<Previous Entry]
[^^Up^^]
[Next Entry>>]
[Menu]
[About The Guide]
Passing By Reference
Sometimes you don't want to pass the value of an array to a
subroutine but rather the name of it, so that the subroutine
can modify the global copy of it rather than working with a
local copy. In perl you can refer to all the objects of a
particular name by prefixing the name with a star: *foo.
When evaluated, it produces a scalar value that represents
all the objects of that name, including any filehandle, for-
mat or subroutine. When assigned to within a local() opera-
tion, it causes the name mentioned to refer to whatever *
value was assigned to it. Example:
sub doubleary {
local(*someary) = @_;
foreach $elem (@someary) {
$elem *= 2;
}
}
do doubleary(*foo);
do doubleary(*bar);
Assignment to *name is currently recommended only inside a
local(). You can actually assign to *name anywhere, but the
previous referent of *name may be stranded forever. This
may or may not bother you.
Note that scalars are already passed by reference, so you
can modify scalar arguments without using this mechanism by
referring explicitly to the $_[nnn] in question. You can
modify all the elements of an array by passing all the ele-
ments as scalars, but you have to use the * mechanism to
push, pop or change the size of an array. The * mechanism
will probably be more efficient in any case.
Since a *name value contains unprintable binary data, if it
is used as an argument in a print, or as a %s argument in a
printf or sprintf, it then has the value '*name', just so it
prints out pretty.
Even if you don't want to modify an array, this mechanism is
useful for passing multiple arrays in a single LIST, since
normally the LIST mechanism will merge all the array values
so that you can't extract out the individual arrays.
This page created by ng2html v1.05, the Norton guide to HTML conversion utility.
Written by Dave Pearson